package com.cq.base.retrofit.a

import android.util.Log
import com.google.gson.Gson
import okhttp3.FormBody
import okhttp3.Interceptor
import okhttp3.MediaType.Companion.toMediaTypeOrNull
import okhttp3.OkHttpClient
import okhttp3.RequestBody
import okhttp3.logging.HttpLoggingInterceptor
import retrofit2.Retrofit
import retrofit2.converter.gson.GsonConverterFactory
import java.util.concurrent.TimeUnit

/**
 * 作者: CQ
 * 日期: 2021-06-03
 * 说明:
 */
class Retrofit2(baseUrl: String, valuesMap: Map<String, String>) {

    companion object {
        private var url: String = "https://www.wanandroid.com/"

        @Volatile
        private var retrofit2: Retrofit2? = null

        @Volatile
        private var retrofit: Retrofit? = null

        // 默认url头部
        fun getInstance(): Retrofit2 {
            return retrofit2 ?: synchronized(Retrofit2::class.java) {
                retrofit2 ?: Retrofit2(url, mutableMapOf())
            }
        }

        // 自定义url头部
        fun getInstance(baseUrl: String): Retrofit2 {
            if (baseUrl != url) { // 如果本地url和上次rul不同，则重新初始化工具类
                retrofit2 = null
                url = baseUrl
            }
            return retrofit2 ?: synchronized(Retrofit2::class.java) {
                retrofit2 ?: Retrofit2(url, mutableMapOf())
            }
        }

        // 自定义头部 + post参数插入url （post传参+json数据上传）
        fun getInstance(baseUrl: String, map: Map<String, String>?): Retrofit2 {
            if (baseUrl != url) { // 如果本地url和上次rul不同，则重新初始化工具类
                retrofit2 = null
                url = baseUrl
            }
            return retrofit2 ?: synchronized(Retrofit2::class.java) {
                retrofit2 ?: Retrofit2(baseUrl, map!!)
            }
        }

        fun clear() {
            retrofit = null
            retrofit2 = null
        }
    }

    init {
        val gson = Gson().newBuilder().setLenient().serializeNulls().create()
        val okHttpClient =
            OkHttpClient.Builder().connectTimeout(20, TimeUnit.SECONDS).readTimeout(20, TimeUnit.SECONDS).addInterceptor(Interceptor {
                var request = it.request()
                if (request.method.equals("POST", true) && valuesMap.isNotEmpty()) { // 如果是post模式
                    val formBodyBuilder = FormBody.Builder()
                    for ((key, value) in valuesMap.entries) {
                        formBodyBuilder.add(key, value)
                    }
                    request = request.newBuilder().post(formBodyBuilder.build()).build()
                }
                it.proceed(request)
            }).addInterceptor(initLogInterceptor()).build()
        retrofit =
            Retrofit.Builder().baseUrl(baseUrl).client(okHttpClient).addConverterFactory(GsonConverterFactory.create(gson)).build()
    }

    /**
     * 日志拦截器
     */
    private fun initLogInterceptor(): HttpLoggingInterceptor {
        val interceptor = HttpLoggingInterceptor(object : HttpLoggingInterceptor.Logger {
            override fun log(message: String) {
                Log.i("Retrofit", message)
            }
        })
        interceptor.level = HttpLoggingInterceptor.Level.BODY

        return interceptor
    }

    /**
     * 具体服务实例化
     **/
    inline fun <reified T : Api> getService(): T {
        return create(T::class.java)
    }

    fun <T : Api> create(clazz: Class<T>): T = retrofit!!.create(clazz)


}

fun RequestBody.onCreateBody(map: Map<String, String>): RequestBody {
    val data = StringBuffer()
    if (map.isNotEmpty()) {
        map.forEach {
            data.append(it.key).append("=").append(it.value).append("&")
        }
    }
    val str = if (data.isEmpty()) {
        ""
    } else data.substring(0, data.length - 1)
    return RequestBody.create("application/x-www-form-urlencoded; charset=utf-8".toMediaTypeOrNull(), str)
}